#include "forgotpwd.h"
#include <QMessageBox>
#include <QDebug>
#include "resetpwd.h"
#include <QSqlQuery>
#include "mysql.h"

ForgotPwd::ForgotPwd(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ForgotPwd)
{
    ui->setupUi(this);
    setWindowTitle("忘记密码");
    qDebug() << "ForgotPwd 窗口创建";
}

ForgotPwd::~ForgotPwd()
{
    delete ui;
    qDebug() << "ForgotPwd 窗口销毁";
}

void ForgotPwd::on_confirmButton_clicked()
{
    // 获取用户输入的账号
    QString account = ui->lineEdit_id->text().trimmed();

    // 检查账号是否为空
    if (account.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入账号！");
        return;
    }

    mysql db;
    if (!db.initDatabase()) {
        QMessageBox::critical(this, "错误", "数据库连接失败！");
        return;
    }
    QSqlQuery query(db.getDatabase());
    query.prepare("SELECT question, answer FROM users WHERE id=?");
    query.addBindValue(account);
    if (query.exec() && query.next()) {
        QString question = query.value(0).toString();
        QString answer = query.value(1).toString();
        Resetpwd *resetWin = new Resetpwd(nullptr);
        resetWin->setAccountAndQuestion(account, question, answer);
        resetWin->show();
        this->close();
    } else {
        QMessageBox::warning(this, "提示", "没有该账号！");
    }
}

// 重写关闭事件，发射自定义信号
void ForgotPwd::closeEvent(QCloseEvent *event)
{
    QWidget::closeEvent(event);
    emit closed();  // 发射自定义信号
    qDebug() << "ForgotPwd 窗口关闭，发射 closed() 信号";
}
